﻿using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Sykj.Components
{
    /// <summary>
    /// 自定义授权中间件
    /// </summary>
    public class JwtAuthorizationMiddleware
    {
        /// <summary>
        /// 管道代理对象
        /// </summary>
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        public JwtAuthorizationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 调用管道
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext httpContext)
        {
            //检测是否包含'Authorization'请求头，如果不包含则直接放行
            if (!httpContext.Request.Headers.ContainsKey(Constant.AUTHORIZATION))
            {
                return _next(httpContext);
            }
            var tokenHeader = httpContext.Request.Headers[Constant.AUTHORIZATION];
            tokenHeader = tokenHeader.ToString().Substring("Bearer ".Length).Trim();
            TokenModel tokenModel = JwtHelper.SerializeJWT(tokenHeader);
            List<Claim> claimList = new List<Claim>();
            claimList.Add(new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid));
            claimList.Add(new Claim(JwtRegisteredClaimNames.NameId, tokenModel.UserName));
            claimList.Add(new Claim("Role", tokenModel.Role));
            claimList.Add(new Claim("Project", tokenModel.Project));
            
            var identity = new ClaimsIdentity(claimList);
            httpContext.User = new ClaimsPrincipal(identity);

            return _next(httpContext);
        }
    }
}
